const {
    app,
    remote
} = require('electron')
const fs = require("fs");
const http = require('http');
const path = require('path');
const AdmZip = require('adm-zip-iconv')

const compressing = require('compressing');

module.exports = function (dir_name, package_path, callback) {

    // http://118.144.87.37:13083/group1/M00/00/1E/CgIEDl4CzMOAOIEZAA2FQMqUquA205.zip

    // const BrowserWindow = remote.BrowserWindow;

    const downloadUrl = package_path,
        backupUrl = './zip/config.json'
    let config = {}
    try {
        config = require('./zip/config')
    } catch (e) {
        fs.writeFileSync(path.resolve(__dirname, backupUrl), JSON.stringify({}, null, 2))
    }
    if (!config.hasOwnProperty(dir_name) || config[dir_name].pkg_url !== package_path) {
        let params = require(path.resolve(__dirname, backupUrl))
        console.log('@', downloadUrl)
        const fileName = /(?<=\/)[^\/]+(?=\.zip$)/.exec(downloadUrl)[0];
        downloadFileAsync(downloadUrl, path.resolve(__dirname, "zip", fileName + ".zip"))
            .then(res => {
                let unzip = new AdmZip(path.resolve(__dirname, "zip", fileName + ".zip"), 'GBK')
                try {
                    fs.rmdirSync(path.resolve(__dirname, "./src", dir_name))
                    console.log(2)
                } catch (e) {
                    console.log('不存在目录:', dir_name)
                }
                unzip.extractAllTo(path.resolve(__dirname, "./src", dir_name), true)
                const list = fs.readdirSync(path.resolve(__dirname, "./src", dir_name))
                let url = ''
                if (!list.includes('index.html') && list.length === 1) {
                    url = path.resolve(path.resolve(__dirname, "./src", dir_name), list[0])
                    console.log(url)
                    params[dir_name] = {
                        pkg_url: package_path,
                        local_path: url
                    }
                    fs.writeFileSync(backupUrl, JSON.stringify(params, null, 2), 'utf8')
                }
                callback()
            })
            .catch(err => {
                callback(err)
            })
    }
}

function downloadFileAsync(uri, dest) {
    return new Promise((resolve, reject) => {
        // 确保dest路径存在
        const file = fs.createWriteStream(dest);

        http.get(uri, (res) => {
            if (res.statusCode !== 200) {
                reject(res);
                return;
            }

            res.on('end', () => {
                console.log('download end');
            });

            // 进度、超时等

            file.on('finish', () => {
                console.log('finish write file')
                file.close(resolve);
            }).on('error', (err) => {
                console.error(err)
                fs.unlink(dest);
                reject(err.message);
            })

            res.pipe(file);
        });
    });
}